package example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Flink DataStream WordCount
 */
public class StreamWordCount {

    /**
     * Spark 程序编写
     * 1. 创建Spark程序执行环境 SparkContext
     * 2. 读取数据 创建DStream
     * 3. 调用Transfermation 处理数据
     * 4. 调用action 执行job 保存处理好的数据
     * 5. 释放资源
     */
    public static void main(String[] args) throws Exception {
        // 创建Flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 读取数据 创建DataStream
        DataStreamSource<String> data = env.socketTextStream(args[0], Integer.parseInt(args[1]));
        // 调用transformation 处理数据
        SingleOutputStreamOperator<String> words = data.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                // 将单词和分割
                String[] words = s.split(" ");
                // 存放到Collector
                for (String word : words) {
                    collector.collect(word);
                }
            }
        });
        // 将单词和1组合
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }
        });
        // 将单词根据key分组
        KeyedStream<Tuple2<String, Integer>, String> keyed = wordAndOne.keyBy(t -> t.f0);
        // 将单词聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = keyed.sum(1);
        // 打印
        sum.print();
        // 执行Flink程序 抛出异常 不然不好找到异常信息
        env.execute();

    }
}
